import { createRouter, createWebHistory } from 'vue-router';
import { useConfigStore } from '@/stores/config';

const LoginView = () => import('@/views/LoginView.vue');
const DashboardView = () => import('@/views/DashboardView.vue');

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { public: true }
    },
    {
      path: '/',
      name: 'dashboard',
      component: DashboardView
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/'
    }
  ]
});

router.beforeEach((to, _from, next) => {
  const config = useConfigStore();
  if (!to.meta.public && !config.isAuthenticated) {
    next({ name: 'login', query: { redirect: to.fullPath } });
    return;
  }
  if (to.name === 'login' && config.isAuthenticated) {
    next({ name: 'dashboard' });
    return;
  }
  next();
});

export default router;
